package com.rlz.net

import android.app.Application
import com.rlz.net.Interceptor.NetCacheInterceptor
import com.rlz.net.Interceptor.NetOfflineInterceptor
import com.rlz.net.Interceptor.RequestInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * Created by RLZ
 * on 2021/4/16
 *
 */
class NetManager {


    companion object {
        val instance: NetManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetManager()
        }

        const val BASE_URL: String = BuildConfig.BASE_URL

        const val CONNECTION_TIMEOUT = 10

        const val READ_TIMEOUT = 30

        lateinit var sApplication: Application

        fun init(application: Application) {
            sApplication = application
        }

        const val MAX_SIZE = 1024 * 1024 * 50
    }


    private fun getRetrofit(): Retrofit {

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(createOkHttp())
            .build()
    }

    private fun createOkHttp(): OkHttpClient {
        val cache = Cache(File(sApplication.cacheDir.path), MAX_SIZE.toLong())
        return OkHttpClient.Builder()
            .addInterceptor(RequestInterceptor())
            .addInterceptor(NetCacheInterceptor.instance)
            .addInterceptor(NetOfflineInterceptor.instance)
            .cache(cache)
            .readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .connectTimeout(CONNECTION_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build()
    }


    fun <T> getService(service: Class<T>?): T {
        return getRetrofit().create(service)
    }
}